<template>
    <div class="myForm">
        <el-form ref="rgForm" :rules="rules" :model="rgForm" label-width="80px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="姓名" required prop="name">
                        <el-input v-model="rgForm.name"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="性别" required>
                        <el-select v-model="rgForm.gender" placeholder="请选择">
                            <el-option v-for="item in genders" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="政治面貌" required prop="zzmm">
                        <el-input v-model="rgForm.zzmm"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="民族" required prop="mz">
                        <el-select v-model="rgForm.mz" placeholder="请选择">
                            <el-option v-for="item in nation_data" :key="item.value" :label="item.label" :value="item.value"> </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item label="健康状况" required prop="jkzk">
                        <el-input v-model="rgForm.jkzk"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="籍贯" required prop="jg">
                        <el-input v-model="rgForm.jg"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="身份证号" required prop="id">
                        <el-input v-model="rgForm.id"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="报考单位及岗位" label-width="140px" required prop="bkdw">
                        <el-input v-model="rgForm.bkdw"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="现工作单位及职务" label-width="140px" required prop="gzdw">
                        <el-input v-model="rgForm.gzdw"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="全日制教育最高学历学位" label-width="180px" prop="qrzxl">
                        <el-input v-model="rgForm.qrzxl"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="16">
                    <el-form-item label="全日制教育毕业院校及所学专业" label-width="220px" prop="qrzxx">
                        <el-input v-model="rgForm.qrzxx"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="在职教育最高学历学位" label-width="180px" prop="zzxl">
                        <el-input v-model="rgForm.zzxl"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="16">
                    <el-form-item label="在职教育毕业院校及所学专业" label-width="220px" prop="zzxx">
                        <el-input v-model="rgForm.zzxx"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="专业技术职称" label-width="110px" prop="zyjszc">
                        <el-input v-model="rgForm.zyjszc"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="懂何种外语及熟悉程度" label-width="180px" prop="wycd">
                        <el-input v-model="rgForm.wycd"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="手机号码" label-width="80px" prop="phone">
                        <el-input v-model="rgForm.phone"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="工作学习简历(从高中填起)" label-width="110px" prop="gzxxjl">
                        <el-input v-model="rgForm.gzxxjl" type="textarea" :rows="3"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="奖惩情况" label-width="110px" prop="jcqk">
                        <el-input v-model="rgForm.jcqk"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-table :data="rgForm.jtcy" border style="width: 95%; margin: 0 auto">
                    <el-table-column width="100" label="与本人关系">
                        <template slot-scope="{ row }">
                            <template v-if="row.editable">
                                <el-input v-model="row.gx" />
                            </template>
                            <span v-else>{{ row.gx }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column width="100" label="姓名">
                        <template slot-scope="{ row }">
                            <template v-if="row.editable">
                                <el-input v-model="row.name" />
                            </template>
                            <span v-else>{{ row.name }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column width="120" label="出生年月">
                        <template slot-scope="{ row }">
                            <template v-if="row.editable">
                                <el-input v-model="row.born" />
                            </template>
                            <span v-else>{{ row.born }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column width="120" label="政治面貌">
                        <template slot-scope="{ row }">
                            <template v-if="row.editable">
                                <el-input v-model="row.zzmm" />
                            </template>
                            <span v-else>{{ row.zzmm }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="工作单位及职务">
                        <template slot-scope="{ row }">
                            <template v-if="row.editable">
                                <el-input v-model="row.gzdw" />
                            </template>
                            <span v-else>{{ row.gzdw }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="100">
                        <template slot-scope="{ row }">
                            <el-button type="text" size="small" @click="row.editable = false">保存</el-button>
                            <el-button type="text" size="small" @click="row.editable = true">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-row>
            <el-row>
                <el-col :span="24" prop="txdz">
                    <el-form-item label="通讯地址" label-width="100px">
                        <el-input v-model="rgForm.txdz"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" prop="brxxdz">
                    <el-form-item label="本人详细住址" label-width="100px">
                        <el-input v-model="rgForm.brxxzz"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24" prop="memo">
                    <el-form-item label="备注" label-width="100px">
                        <el-input v-model="rgForm.memo"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div class="bottom">
            <el-upload
                style="width: 45%"
                action
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
                <img v-if="myhead" :src="myhead" class="avatar" style="width: 100%; height: 100%" />
                <div v-else>点击添加头像</div>
            </el-upload>
            <div class="btns">
                <el-button type="primary" @click="saveData" style="width: 100px; height: 32px">保存</el-button>
                <el-button type="primary" @click="confirmBox" style="width: 100px; height: 32px">打印登记表</el-button>
            </div>
        </div>
        <canvas id="table" style="display: none"></canvas>
    </div>
</template>

<script>
import {
    saveForm,
    getBaseInfo,
    getUserInfo,
    getInfoList
} from '@/api/ewgAndEnlist'
import { uploadImg } from '@/api/resumeEdit';
export default {
    props:['formData'],
    data() {
        var validRules = {
            checkAge : (rule, value, callback) => {
                if (!value) {
                return callback(new Error('年龄不能为空'));
                }
                setTimeout(() => {
                if (!Number.isInteger(value)) {
                    callback(new Error('请输入数字值'));
                } else {
                    if (value < 18) {
                        callback(new Error('必须年满18岁'));
                    } else {
                    callback();
                    }
                }
                }, 1000);
            },
            v_phone: (rule, value, callback) => {
                if(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(value)) {
                    callback()
                }else{
                    callback(new Error('电话号码输入有误'));
                }
            }
        }
        return {
            rgForm: {
                zzmm: '中共党员',
                name: '张三',
                gender: '男',
                born: '200001',
                mz: '汉族',
                jkzk: '健康',
                bkdw: '清华大学计算机科学与技术',
                gzdw: '华为科技有限公司项目经理',
                qrzxl: '本科',
                qrzxx: '复旦大学计算机科学与技术',
                zzxl: '本科',
                zzxx: '复旦大学计算机科学与技术',

                zyjszc: '教授',
                wycd: '大学英语四级',
                phone: '18812312312',

                gzxxjl: '衡水中学 清华大学 哈佛大学',

                jcqk: '乌拉乌拉',

                jtcy: [
                    {
                        gx: '父亲',
                        name: '张麻子',
                        born: '1965',
                        zzmm: '群众',
                        gzdw: '劳务局局长',
                        editable: false
                    },
                    {
                        gx: '父亲',
                        name: '张麻子',
                        born: '1965',
                        zzmm: '群众',
                        gzdw: '劳务局局长',
                        editable: false
                    },
                    {
                        gx: '父亲',
                        name: '张麻子',
                        born: '1965',
                        zzmm: '群众',
                        gzdw: '劳务局局长',
                        editable: false
                    },
                    {
                        gx: '父亲',
                        name: '张麻子',
                        born: '1965',
                        zzmm: '群众',
                        gzdw: '劳务局局长',
                        editable: false
                    }
                ],

                txdz: '北京市海淀区上地十街巴拉巴拉',

                brxxzz: '北京市海淀区上地十街巴拉巴拉',

                memo: '哇大苏打实打实大苏打萨达萨达撒旦去我的',
                jg: '四川省',
                // headIcon: headicon,
                id: '999999999999999999'
            },
            nation_data: [
                { value: '汉族', label: '汉族' },
                { value: '蒙古族', label: '蒙古族' },
                { value: '回族', label: '回族' },
                { value: '藏族', label: '藏族' },
                { value: '维吾尔族', label: '维吾尔族' },
                { value: '苗族', label: '苗族' },
                { value: '彝族', label: '彝族' },
                { value: '壮族', label: '壮族' },
                { value: '布依族', label: '布依族' },
                { value: '朝鲜族', label: '朝鲜族' },
                { value: '满族', label: '满族' },
                { value: '侗族', label: '侗族' },
                { value: '瑶族', label: '瑶族' },
                { value: '白族', label: '白族' },
                { value: '土家族', label: '土家族' },
                { value: '哈尼族', label: '哈尼族' },
                { value: '哈萨克族', label: '哈萨克族' },
                { value: '傣族', label: '傣族' },
                { value: '黎族', label: '黎族' },
                { value: '傈僳族', label: '傈僳族' },
                { value: '佤族', label: '佤族' },
                { value: '畲族', label: '畲族' },
                { value: '高山族', label: '高山族' },
                { value: '拉祜族', label: '拉祜族' },
                { value: '水族', label: '水族' },
                { value: '东乡族', label: '东乡族' },
                { value: '纳西族', label: '纳西族' },
                { value: '景颇族', label: '景颇族' },
                { value: '柯尔克孜族', label: '柯尔克孜族' },
                { value: '土族', label: '土族' },
                { value: '达翰尔族', label: '达翰尔族' },
                { value: '么佬族', label: '么佬族' },
                { value: '羌族', label: '羌族' },
                { value: '布朗族', label: '布朗族' },
                { value: '撒拉族', label: '撒拉族' },
                { value: '毛南族', label: '毛南族' },
                { value: '仡佬族', label: '仡佬族' },
                { value: '锡伯族', label: '锡伯族' },
                { value: '阿昌族', label: '阿昌族' },
                { value: '普米族', label: '普米族' },
                { value: '塔吉克族', label: '塔吉克族' },
                { value: '怒族', label: '怒族' },
                { value: '乌孜别克族', label: '乌孜别克族' },
                { value: '俄罗斯族', label: '俄罗斯族' },
                { value: '鄂温克族', label: '鄂温克族' },
                { value: '德昂族', label: '德昂族' },
                { value: '保安族', label: '保安族' },
                { value: '裕固族', label: '裕固族' },
                { value: '京族', label: '京族' },
                { value: '塔塔尔族', label: '塔塔尔族' },
                { value: '独龙族', label: '独龙族' },
                { value: '鄂伦春族', label: '鄂伦春族' },
                { value: '赫哲族', label: '赫哲族' },
                { value: '门巴族', label: '门巴族' },
                { value: '珞巴族', label: '珞巴族' },
                { value: '基诺族', label: '基诺族' }
            ],
            genders: [
                { label: '男', value: '男' },
                { label: '女', value: '女' }
            ],
            bgImg: require('@/assets/print/rollcall.png'),
            myhead: '',
            dialogVisible: false,
            rules: {
                name: [
                        { required: true, message: '请输入活动名称', trigger: 'blur' },
                        { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
                    ],
                zzmm:[
                    { required: true, message: '请输入政治面貌', trigger: 'blur' },
                ],
                gender:[
                    { required: true, message: '请选择性别', trigger: 'blur' },
                ],
                born:[
                    { required: true, message: '请输入出生年月', trigger: 'blur' },
                ],
                mz:[
                    { required: true, message: '请选择民族', trigger: 'blur' },
                ],
                jkzk:[
                    { required: true, message: '请输入健康情况', trigger: 'blur' },
                ],
                bkdw:[
                    { required: true, message: '请输入报考单位', trigger: 'blur' },
                ],
                gzdw:[
                    { required: true, message: '请输入现工作单位及职务', trigger: 'blur' },
                ],

                zyjszc:[
                    { required: true, message: '请输入专业技术职称', trigger: 'blur' },
                ],
                phone:[
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { validator: validRules.v_phone, trigger: ['blur', 'change'] }
                ],

                gzxxjl:[
                    { required: true, message: '请输入工作学习简历', trigger: 'blur' },
                ],
            }
        };
    },
    methods: {
        editRow(index) {
            this.rgForm['jtcy']['editable'] = true;
        },
        saveRow() {
            this.rgForm['jtcy']['editable'] = true;
        },
        drawCanvas(imgObj, data) {
            var c = document.getElementById('table');
            c.width = 2481;
            c.height = 3508;
            var ctx = c.getContext('2d');
            ctx.font = "bold 36px 'SimSun'";
            ctx.fillStyle = '#151515';

            ctx.drawImage(imgObj, 0, 0); // 背景图

            //   ctx.fillText(data.year, 175, 176) // 年份
            ctx.font = "bold 45px 'SimSun'";
            ctx.fillText(data.name, 620, 600); // 姓名
            ctx.fillText(data.gender, 1120, 600); // 性别
            ctx.fillText(data.zzmm, 1620, 600); // 政治面貌
            // +120
            ctx.fillText(data.born, 620, 720); // 出生年月
            ctx.fillText(data.mz, 1120, 720); // 民族
            ctx.fillText(data.jkzk, 1620, 720); // 健康状况
            // +120
            ctx.fillText(data.jg, 620, 840); // 籍贯
            ctx.fillText(data.id, 1120, 840); // 身份证号
            // +140
            ctx.fillText(data.bkdw, 620, 980); // 报考单位及岗位
            // +130
            ctx.fillText(data.gzdw, 620, 1110); // 现工作单位及职务

            ctx.drawImage(data.headIcon, 1835, 526, 420, 636); // 现工作单位及职务
            // +170
            ctx.fillText(data.qrzxl, 620, 1280); // 全日制学历
            ctx.fillText(data.qrzxx, 1420, 1280); // 全日制学校
            // +200
            ctx.fillText(data.zzxl, 620, 1480); // 在职学历
            ctx.fillText(data.zzxx, 1420, 1480); // 在职学校
            // +160
            ctx.fillText(data.zyjszc, 620, 1640);
            ctx.fillText(data.wycd, 1260, 1640);
            ctx.fillText(data.phone, 1760, 1640);

            ctx.fillText(data.gzxxjl, 620, 1780);

            ctx.fillText(data.jcqk, 620, 2000);
            // +230

            // +100
            //   ctx.fillText(data.jcqk, 620, 2330)
            // 家庭关系
            for (let v in data.jtcy) {
                ctx.fillText(data.jtcy[v].gx, 620, 2230 + v * 100);
                ctx.fillText(data.jtcy[v].name, 850, 2230 + v * 100); // +230
                ctx.fillText(data.jtcy[v].born, 1060, 2230 + v * 100); // +210
                ctx.fillText(data.jtcy[v].zzmm, 1350, 2230 + v * 100); // +290
                ctx.fillText(data.jtcy[v].gzdw, 1660, 2230 + v * 100); // +310
            }
            ctx.fillText(data.txdz, 620, 2630);
            ctx.fillText(data.brxxzz, 620, 2740);
            ctx.fillText(data.memo, 620, 3110);

            //   ctx.fillText(data.gender, 640, 416) // 性别
            //   ctx.fillText(data.school, 410, 485) // 位置
            // this.$('#table').show()
        },
        drawData(bgImg, headicon) {
            this.drawCanvas(bgImg, Object.assign(this.rgForm, { headIcon: headicon }));
        },
        generateDOM(type, id) {
            let node = null;
            node = document.getElementById(id);
            if (node) {
                node.remove();
            }
            node = document.createElement(type);
            node.id = id;
            node.setAttribute('style', 'display:none;');
            return node;
        },
        loadImage(obj, url) {
            return new Promise((resolve, reject) => {
                var img = new Image();
                img.src = url;
                // 判断图片是否在缓存中
                if (img.complete) {
                    resolve(img, obj);
                }
                // 图片加载到浏览器的缓存中回调函数
                img.onload = function () {
                    resolve(img, obj);
                };
                img.onerror = function (err) {
                    reject(err);
                };
            });
        },
        print(htmlTitle) {
            // this.$shot(document.getElementById('table'), {logging: false, scale: 2}).then((canvas) => {
            let canvas = document.getElementById('table');
            document.documentElement.scrollTop = 0;
            let contentWidth = canvas.width;
            let contentHeight = canvas.height;
            // 将canvas转为base64图片
            let pageData = canvas.toDataURL('image/jpeg', 1.0);

            // 设置pdf的尺寸，pdf要使用pt单位 已知 1pt/1px = 0.75   pt = (px/scale)* 0.75
            // 2为上面的scale 缩放了2倍
            let pdfX = ((contentWidth + 10) / 2) * 0.75;
            let pdfY = ((contentHeight + 100) / 2) * 0.75; // 500为底部留白

            // 设置内容图片的尺寸，img是pt单位
            let imgX = pdfX;
            let imgY = (contentHeight / 2) * 0.75; // 内容图片这里不需要留白的距离

            // 初始化jspdf 第一个参数方向：默认''时为纵向，第二个参数设置pdf内容图片使用的长度单位为pt，第三个参数为PDF的大小，单位是pt
            let PDF = new this.$pdf('', 'pt', [pdfX, pdfY]);

            // 将内容图片添加到pdf中，因为内容宽高和pdf宽高一样，就只需要一页，位置就是 0,0
            PDF.addImage(pageData, 'jpeg', 0, 0, imgX, imgY);
            PDF.save(htmlTitle);
            // })
        },
        printRegTable() {
            let headnode = this.generateDOM('img', 'heads');
            let bgnode = this.generateDOM('img', 'bg');
            let list = [];
            list.push(this.loadImage(bgnode, this.bgImg));
            list.push(this.loadImage(headnode, this.myhead));
            Promise.all(list).then((datas) => {
                this.drawData(datas[0], datas[1]);
                this.print('登记表');
            });
        },
        // 上传图片
        postFile(params) {
            let msg = params.file.name.substring(params.file.name.lastIndexOf('.') + 1);
            const extension = msg === 'jpg';
            const extension2 = msg === 'png';
            const extension3 = msg === 'bmp';
            if (!extension && !extension2 && !extension3) {
                this.$message({
                    message: '文件只能是 jpg、png、bmp类型!',
                    type: 'warning'
                });
                return false;
            }
            if (params.file.size > 500 * 1024) {
                this.$confirm('图片不能超过500kb，请重新上传图片', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                });
                return false;
            } else {
                let formData = new FormData();
                formData.append('file', params.file);
                uploadImg(formData).then((res) => {
                    console.log(res, '头像');
                    if (res.success) {
                        this.$message.success('图片上传成功')
                        this.myhead = res.data.fileUrl;
                    } else {
                        this.$message.error(`${res.msg}`);
                    }
                });
            }
        },
        handleAvatarSuccess(res, file) {
            console.log(file.raw);
            this.myhead = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            // var reader = new FileReader();
            // reader.readAsDataURL(file);
            // //监听文件读取结束后事件
            // reader.onloadend = (e) => {
            //     this.myhead = e.target.result;
            //     // `<img src=${e.target.result} ></img>`;
            // };
            this.postFile({file})
            return isJPG && isLt2M;
        },
        validData () {
            if (!this.myhead) {
                this.$message({
                message: '请上传头像',
                type: 'warning'
                });
                return false
            }
            this.$refs['rgForm'].validate((valid) => {
            if (valid) {
                alert('submit!');
                return false
            } else {
                console.log('error submit!!');
                return false;
            }
            });
        },
        confirmBox() {
            if(!this.validData())return
            this.$confirm('确定要打印文件？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '在检查一下',
                type: 'warning'
            }).then(() => {
                this.printRegTable()
            }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
        },
        saveData () {
            let obj = {
                id:'',
                title:'',
                name:'',
                sex:'',
                politicalStatus:'',
                birthday:'',
                nation:'',
                health:'',
                fromplace:'',
                idCard:'',
                examfor:'',
                curworkcomp:'',
                photo:'',
                education:'',
                school:'',
                major:'',
                education2:'',
                school2:'',
                major2:'',
                techTitle:'',
                lang:'',
                phone:'',
                experience:'',
                reward:'',
                mailingAddress:'',
                note:''
            }
            saveForm(obj).then(res =>{
                console.log(res)
            })
        },
        getBaseInfo () {
           getBaseInfo().then(res => {
               console.log(res,'获取基础信息');
               let obj = {
                   title:'',
                   name:'',
                   sex:'',
                   politicalStatus:'',
                   birthday:'',
                   nation:'',
                   idCard:'',
                   photo:'',
                   education:'',
                   major:'',
                   phone:'',
                   mailingAddress:'',
               }
           })
        },
        getDetailsInfo () {
            getUserInfo({id:''}).then(res=>{
                console.log(res,'获取报表详细信息');
            })
        },
        getList () {
            getInfoList().then( res=>{
                console.log(res, '列表信息');
            })
        }
    }
};
</script>

<style>
.myForm {
    background-color: #ffffff;
    margin-bottom: 5vw;
    padding: 5px;
    border-radius: 2px;
}
.myForm .bottom {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
}
</style>